package com.cly.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.constant.CategoryConstant;
import com.cly.domain.Category;
import com.cly.mapper.CategoryMapper;
import com.cly.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * 命名空间隔离
 */
@Service
@Slf4j
@CacheConfig(cacheNames = "com.cly.service.impl.CategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 全查询商品分类
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_ALL_PREFIX)
    public List<Category> list() {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .orderByDesc(Category::getUpdateTime)
        );
        return categoryList;
    }

    /**
     * 查询商品父级分类
     * 也需要缓存
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
    public List<Category> findCategoryParent() {
        List<Category> categoryList = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId, 0L)
                .eq(Category::getStatus, 1)
        );
        return categoryList;
    }

    /**
     * 新增商品分类
     * 删除所有缓存
     * @param category
     * @return
     */
    @Override
    @Caching(evict = {
            @CacheEvict(key = CategoryConstant.CATEGORY_ALL_PREFIX),
            @CacheEvict(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
    })
    public boolean save(Category category) {
        log.info("新增商品分类{}", JSON.toJSONString(category));
        category.setRecTime(new Date());
        category.setUpdateTime(new Date());
        category.setShopId(1L);
        // 新增商品分类 1.新增父节点 2.新增子节点
        Long parentId = category.getParentId();
        if (parentId == null || parentId.equals(0L)) {
            // 说明父级分类
            parentId = 0L;
            category.setGrade(1);
        } else {
            // 说明子分类  需要查询一下他的父节点
            Category parent = categoryMapper.selectById(parentId);
            if (ObjectUtils.isEmpty(parent)) {
                throw new IllegalArgumentException("新增商品分类时父节点不存在");
            }
            category.setGrade(2);
        }
        return super.save(category);
    }
}
